<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'material:check:pmMaterialcheck:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #clSelect>
        <!--  -->
        <ListSelect
          selectType="materialSelect"
          :checkbox="true"
          :params="queryParams"
          :selectList="listSelectRef"
          @select="handSelect"
        />
      </template>
      <template #pmMaterialchecksList>
        <BasicTable
          @register="registerPmMaterialchecksTable"
          @row-click="handlePmMaterialchecksRowClick"
        >
          <template #childUpload="{ record: childRecord }">
            <BasicUpload
              v-model:value="childRecord.dataMap"
              :bizKey="childRecord.id"
              :bizType="'pmMaterialcheck_image_child'"
              :uploadType="'image'"
              :loadTime="record.__t"
              disabled
            />
          </template>
        </BasicTable>
        <a-button
          class="mt-2"
          @click="handlePmMaterialchecksAdd"
          :disabled="true"
          v-auth="'material:check:pmMaterialcheck:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('选择材料') }}
        </a-button>
      </template>
    </BasicForm>
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="material_check"
        completeText="提交"
        :loading="loadingRef"
        :auth="'material:check:pmMaterialcheck:edit'"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsMaterialCheckPmMaterialcheckForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    PmMaterialcheck,
    pmMaterialcheckSave,
    pmMaterialcheckForm,
  } from '/@/api/material/check/pmMaterialcheck';
  import { BpmButton } from '/@/components/Bpm';
  import { BasicUpload } from '/@/components/Upload';
  import { pmProjectinformationTreeData } from '/@/api/proj/info/pmProjectinformation';
  import { ListSelect } from '/@/components/ListSelect';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('material.check.pmMaterialcheck');
  const { showMessage } = useMessage();
  const record = ref<PmMaterialcheck>({} as PmMaterialcheck);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增材料抽检') : t('编辑材料抽检'),
  }));

  const loadingRef = ref(false);
  let listSelectRef = ref([]);
  let queryParams = ref({});

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('工程名称'),
      field: 'projectno',
      fieldLabel: 'projectname',
      component: 'TreeSelect',
      componentProps: {
        api: pmProjectinformationTreeData,
        params: { isShowCode: true },
        canSelectParent: false,
        allowClear: false,
        onChange: async (e) => {
          queryParams.value = {
            pcode: e,
          };
          let arr = await pmMaterialchecksTable.getDataSource();
          let arrNew = [...arr];
          arrNew.forEach(async (item, index) => {
            console.log(index);
            await pmMaterialchecksTable.deleteTableDataRecord(item);
          });
        },
        disabled: true,
      },
      required: true,
    },
    {
      label: t('工程编号'),
      field: 'projectno',
      component: 'Input',
      componentProps: {
        maxlength: 500,
      },
      required: true,
      dynamicDisabled: true,
    },
    {
      label: t('材料清单'),
      field: 'materialInfo',
      component: 'Input',
      slot: 'clSelect',
      show: false,
      colProps: { lg: 24, md: 24 },
      dynamicDisabled: true,
    },
    {
      label: t('抽检结果'),
      field: 'state',
      component: 'RadioGroup',
      componentProps: {
        dictType: 'zf_material_check_status',
      },
      required: true,
      dynamicDisabled: true,
    },
    {
      label: t('抽检人'),
      field: 'checker',
      component: 'Input',
      componentProps: {
        maxlength: 50,
      },
      ifShow: false,
      dynamicDisabled: true,
    },
    {
      label: t('抽检日期'),
      field: 'checkdate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        //showTime: { format: 'HH:mm' },
      },
      required: true,
      dynamicDisabled: true,
    },
    {
      label: t('备注'),
      field: 'remark',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
        rows: 5,
      },
      colProps: { lg: 24, md: 24 },
      dynamicDisabled: true,
    },
    {
      label: t('复核人'),
      field: 'reviewer',
      component: 'Input',
      componentProps: {
        maxlength: 50,
      },
      ifShow: false,
      dynamicDisabled: true,
    },
    {
      label: t('复核日期'),
      field: 'reviewdate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
      ifShow: false,
      dynamicDisabled: true,
    },
    {
      label: t('处理人'),
      field: 'dealwithper',
      component: 'Input',
      componentProps: {
        maxlength: 50,
      },
      ifShow: false,
      dynamicDisabled: true,
    },
    {
      label: t('处理时间'),
      field: 'dealwithdate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
      ifShow: false,
      dynamicDisabled: true,
    },
    {
      label: t('处理结果'),
      field: 'dealwithresult',
      component: 'Input',
      componentProps: {
        maxlength: -1,
      },
      ifShow: false,
      dynamicDisabled: true,
    },
    {
      label: t('创建时间'),
      field: 'createtime',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
      ifShow: false,
      dynamicDisabled: true,
    },
    {
      label: t('处理记录时间'),
      field: 'dealwithoptime',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
      ifShow: false,
      dynamicDisabled: true,
    },
    {
      label: t('图片上传'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'pmMaterialcheck_image',
        uploadType: 'image',
        isPreview: true,
      },
      colProps: { lg: 24, md: 24 },
      dynamicDisabled: true,
    },
    {
      label: t('材料明细'),
      field: 'pmMaterialchecksList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'pmMaterialchecksList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, getFieldsValue, validate, updateSchema }] =
    useForm({
      labelWidth: 120,
      schemas: inputFormSchemas,
      baseColProps: { lg: 12, md: 12 },
    });

  const [registerPmMaterialchecksTable, pmMaterialchecksTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handlePmMaterialchecksDelete.bind(this, record),
          },
          auth: 'material:check:pmMaterialcheck:edit',
          disabled: true,
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setPmMaterialchecksTableData(_res: Recordable) {
    pmMaterialchecksTable.setColumns([
      {
        title: t('创建时间'),
        dataIndex: 'createtime',
        width: 215,
        align: 'center',
        editRow: true,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD HH:mm',
          showTime: { format: 'HH:mm' },
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('name'),
        dataIndex: 'name',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 50,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('物料编码'),
        dataIndex: 'metercode',
        width: 100,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 50,
        },
        editRule: false,
      },
      {
        title: t('物料名称'),
        dataIndex: 'metername',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 50,
        },
        editRule: false,
      },
      {
        title: t('规格型号'),
        dataIndex: 'mstd',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 50,
        },
        editRule: false,
      },
      {
        title: t('图片'),
        dataIndex: 'dataMap',
        width: 130,
        align: 'left',
        slot: 'childUpload',
        // componentProps: {
        //   loadTime: computed(() => record.value.__t),
        //   bizKey: computed(() => record.value.id),
        //   bizType: 'pmMaterialcheck_image_child',
        //   uploadType: 'image',
        // },
        // colProps: { lg: 24, md: 24 },
      },
      {
        title: t('备注'),
        dataIndex: 'remarks',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 50,
        },
        editRule: false,
      },
    ]);
    pmMaterialchecksTable.setTableData(record.value.pmMaterialchecksList || []);
  }

  function handlePmMaterialchecksRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handlePmMaterialchecksAdd() {
    if (!getFieldsValue().projectno) {
      showMessage('请先选择工程！');
      return;
    }
    listSelectRef.value = [];
    document.getElementById('form_item_materialInfo')?.click();
    // pmMaterialchecksTable.insertTableDataRecord({
    //   id: new Date().getTime(),
    //   isNewRecord: true,
    //   editable: true,
    // });
  }

  function handlePmMaterialchecksDelete(record: Recordable) {
    pmMaterialchecksTable.deleteTableDataRecord(record);
  }

  async function getPmMaterialchecksList() {
    let pmMaterialchecksListValid = true;
    let pmMaterialchecksList: Recordable[] = [];
    for (const record of pmMaterialchecksTable.getDataSource()) {
      // if (!(await record.onEdit?.(false, true))) {
      //   pmMaterialchecksListValid = false;
      // }
      pmMaterialchecksList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of pmMaterialchecksTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      pmMaterialchecksList.push({
        ...record,
        status: '1',
      });
    }
    if (!pmMaterialchecksListValid) {
      throw { errorFields: [{ name: ['pmMaterialchecksList'] }] };
    }
    return pmMaterialchecksList;
  }

  async function handSelect(selectData) {
    console.log(selectData);
    let arr = await pmMaterialchecksTable.getDataSource();
    selectData.forEach((item) => {
      let flag = true;
      arr.forEach((res) => {
        if (res.metercode == item.mcode) {
          flag = false;
        }
      });
      if (flag) {
        pmMaterialchecksTable.insertTableDataRecord({
          ...item,
          // id: new Date().getTime() + item.id,
          editable: true,
          isNewRecord: true,
          metercode: item.mcode,
          metername: item.mname,
          mstd: item.mstd,
        });
      }
    });
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await pmMaterialcheckForm(data);
    record.value = (res.pmMaterialcheck || {}) as PmMaterialcheck;
    record.value.__t = new Date().getTime();
    if (record.value.state != undefined) {
      record.value.state = record.value.state + '';
    }
    queryParams.value = {
      pcode: record.value.projectno,
    };
    setFieldsValue(record.value);
    setPmMaterialchecksTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      data.bpm = record.value.bpm; // 流程信息
      data.status = record.value.status; // 提交状态
      loadingRef.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.pmMaterialchecksList = await getPmMaterialchecksList();
      //console.log('submit', params, data, record);
      const res = await pmMaterialcheckSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>
